package ai

import (
	"fmt"
	"regexp"
	"strings"

	"workflow-gui/internal/workflow"
)

// ValidateStage1Output 验证 Stage 1 输出（proposals 字段）
func ValidateStage1Output(output map[string]interface{}) error {
	// 必填字段列表
	requiredFields := []string{
		"priority", "target_users", "key_features",
		"affected_capabilities", "breaking_changes",
	}

	// 检查必填字段
	for _, field := range requiredFields {
		if _, ok := output[field]; !ok {
			return fmt.Errorf("missing required field: %s", field)
		}

		// 检查对应的 _reasoning 字段
		reasoningField := field + "_reasoning"
		if _, ok := output[reasoningField]; !ok {
			return fmt.Errorf("missing reasoning field: %s", reasoningField)
		}
	}

	// 验证 priority 枚举值
	priority, ok := output["priority"].(string)
	if !ok {
		return fmt.Errorf("priority must be a string")
	}
	validPriorities := map[string]bool{"P0": true, "P1": true, "P2": true, "P3": true}
	if !validPriorities[priority] {
		return fmt.Errorf("priority must be one of: P0, P1, P2, P3, got: %s", priority)
	}

	// 验证 target_users 不能是"所有人"
	targetUsers, ok := output["target_users"].(string)
	if !ok {
		return fmt.Errorf("target_users must be a string")
	}
	forbiddenUsers := []string{"所有人", "所有用户", "all users", "everyone"}
	for _, forbidden := range forbiddenUsers {
		if strings.Contains(strings.ToLower(targetUsers), strings.ToLower(forbidden)) {
			return fmt.Errorf("target_users cannot be generic like '%s', must be specific user roles", forbidden)
		}
	}

	// 验证 key_features 至少 2 个
	keyFeatures, ok := output["key_features"].([]interface{})
	if !ok {
		return fmt.Errorf("key_features must be an array")
	}
	if len(keyFeatures) < 2 {
		return fmt.Errorf("key_features must have at least 2 items, got: %d", len(keyFeatures))
	}

	// 验证 affected_capabilities 至少 1 个
	affectedCaps, ok := output["affected_capabilities"].([]interface{})
	if !ok {
		return fmt.Errorf("affected_capabilities must be an array")
	}
	if len(affectedCaps) < 1 {
		return fmt.Errorf("affected_capabilities must have at least 1 item")
	}

	// 验证 breaking_changes 是布尔值
	if _, ok := output["breaking_changes"].(bool); !ok {
		return fmt.Errorf("breaking_changes must be a boolean")
	}

	return nil
}

// ValidateStage2Output 验证 Stage 2 输出（requirements）
func ValidateStage2Output(requirements []workflow.Requirement) error {
	if len(requirements) == 0 {
		return fmt.Errorf("requirements cannot be empty")
	}

	reqIDPattern := regexp.MustCompile(`^req-\d{3}$`)
	validOperations := map[string]bool{
		"ADDED": true, "MODIFIED": true, "REMOVED": true, "RENAMED": true,
	}

	for i, req := range requirements {
		// 验证 req_id 格式
		if !reqIDPattern.MatchString(req.ID) {
			return fmt.Errorf("requirement[%d]: req_id must match format 'req-XXX', got: %s", i, req.ID)
		}

		// 验证 operation 枚举值
		if !validOperations[req.Operation] {
			return fmt.Errorf("requirement[%d]: operation must be one of ADDED/MODIFIED/REMOVED/RENAMED, got: %s", i, req.Operation)
		}

		// 验证 name 长度
		if len(req.Name) < 3 || len(req.Name) > 50 {
			return fmt.Errorf("requirement[%d]: name length must be 3-50 characters, got: %d", i, len(req.Name))
		}

		// 验证 description 包含 SHALL 或 MUST
		if !strings.Contains(req.Description, "SHALL") && !strings.Contains(req.Description, "MUST") {
			return fmt.Errorf("requirement[%d]: description must contain SHALL or MUST keywords", i)
		}
	}

	return nil
}

// ValidateStage3Output 验证 Stage 3 输出（scenarios）
func ValidateStage3Output(scenarios []workflow.Scenario) error {
	if len(scenarios) == 0 {
		return fmt.Errorf("scenarios cannot be empty")
	}

	scenarioIDPattern := regexp.MustCompile(`^scenario-\d{3}$`)

	for i, scenario := range scenarios {
		// 验证 scenario_id 格式
		if !scenarioIDPattern.MatchString(scenario.ID) {
			return fmt.Errorf("scenario[%d]: scenario_id must match format 'scenario-XXX', got: %s", i, scenario.ID)
		}

		// 验证 when 非空
		if strings.TrimSpace(scenario.When) == "" {
			return fmt.Errorf("scenario[%d]: when cannot be empty", i)
		}

		// 验证 then 非空
		if strings.TrimSpace(scenario.Then) == "" {
			return fmt.Errorf("scenario[%d]: then cannot be empty", i)
		}
	}

	return nil
}

// ValidateIterationOutput 验证迭代输出（用户调整）
func ValidateIterationOutput(adjustments interface{}) error {
	// 检查是否为 nil
	if adjustments == nil {
		return fmt.Errorf("adjustments cannot be nil")
	}

	// 检查是否为 map
	adjustMap, ok := adjustments.(map[string]interface{})
	if !ok {
		return fmt.Errorf("adjustments must be a JSON object")
	}

	// 检查是否为空
	if len(adjustMap) == 0 {
		return fmt.Errorf("adjustments cannot be empty")
	}

	return nil
}
